package com.munhrasoft.dinamica.managedbeans;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.primefaces.event.SelectEvent;
import org.primefaces.event.TabChangeEvent;

import com.munhrasoft.dinamica.business.entities.GroupEntity;
import com.munhrasoft.dinamica.business.entities.UserEntity;
import com.munhrasoft.dinamica.business.logic.UserEJB;

@ManagedBean
@ViewScoped
public class UsersController {

    private static Logger     logger    = Logger.getLogger(UsersController.class.getName());

    @EJB
    private UserEJB           userEJB;

    private UserEntity        user      = new UserEntity();
    private UserEntity        pesquser  = new UserEntity();
    private UserEntity        resuser   = new UserEntity();
    private List<UserEntity>  userList  = new ArrayList<UserEntity>();
    private List<GroupEntity> groupList = new ArrayList<GroupEntity>();

    @PostConstruct
    public void init() {
        logger.info("PostConstruct");
        userList = userEJB.fetchAllUsuarios();
        groupList = userEJB.fetchAllGrupos();
        pesquser = new UserEntity();
        user = new UserEntity();
        resuser = new UserEntity();
    }

    public void createUsuario(ActionEvent actionEvent) {
        user = userEJB.createUsuario(user);
        user = new UserEntity();
        pesquser = new UserEntity();
        showMessage(FacesMessage.SEVERITY_INFO, "Operacao Concluida", "Usuario criado com sucesso");
    }

    public void pegarTodosUsuarios(ActionEvent actionEvent) {
        userList = userEJB.fetchAllUsuarios();

        if (!userList.isEmpty()) {
            pesquser = userList.get(0);
        } else {
            showMessage(FacesMessage.SEVERITY_INFO, "Operacao Concluida",
                    "Nenhum usuario encontrado");
        }

    }

    public void saveUsuario(ActionEvent actionEvent) {
        pesquser = userEJB.updateUsuario(pesquser);
        if (pesquser != null) {
            showMessage(FacesMessage.SEVERITY_INFO, "Operacao Concluida",
                    "Usuario atualizado com sucesso");
        } else {
            showMessage(FacesMessage.SEVERITY_ERROR, "Erro", "O usuario nao foi atualizado");
        }
    }

    public void removeUsuario(ActionEvent actionEvent) {
        // TODO nao vai poder deixar remover o admin

        if (pesquser != null) {
            userEJB.removeUsuario(pesquser);
            userList = userEJB.fetchAllUsuarios();
            pesquser = new UserEntity();
            showMessage(FacesMessage.SEVERITY_INFO, "Operacao concluida",
                    "Usuario removido com sucesso");
        } else {
            showMessage(FacesMessage.SEVERITY_ERROR, "Operacao falhou", "Usuario nao selecionado");
        }

    }

    public void rowSelect(SelectEvent event) {
        logger.info("Row select");
        pesquser = resuser;

    }

    public void changeTabView(TabChangeEvent event) {
        logger.info("Tabview changed " + event.getTab().getId());
        userList = userEJB.fetchAllUsuarios();
        pesquser = new UserEntity();
        user = new UserEntity();
    }

    private void showMessage(Severity sev, String summary, String detail) {
        FacesMessage message = new FacesMessage(sev, summary, detail);
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

    public UserEntity getUser() {
        return user;
    }

    public void setUser(UserEntity user) {
        this.user = user;
    }

    public UserEntity getPesquser() {
        return pesquser;
    }

    public void setPesquser(UserEntity pesquser) {
        this.pesquser = pesquser;
    }

    public UserEntity getResuser() {
        return resuser;
    }

    public void setResuser(UserEntity resuser) {
        this.resuser = resuser;
    }

    public List<UserEntity> getUserList() {
        return userList;
    }

    public void setUserList(List<UserEntity> userList) {
        this.userList = userList;
    }

    public List<GroupEntity> getGroupList() {
        return groupList;
    }

    public void setGroupList(List<GroupEntity> groupList) {
        this.groupList = groupList;
    }

}
